/*
 * NodeMCU/ESP8266 act as AP (Access Point) and simplest Web Server
 * to control GPIO D1
 * Connect to AP "NodeAPtest", <password = "password">
 * Open browser, visit 192.168.4.1
 */
#include <ESP8266WiFi.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>

const String HtmlHtml = "<html><head>"
    "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /></head>";
const String HtmlHtmlClose = "</html>";
const String HtmlTitle = "<h1>ESP8266 AP WebServer control</h1><br/>\n";
const String HtmlCenter = "<center>";
const String HtmlLedStateLow = "<big>LED is now <b>ON</b></big><br/>\n";
const String HtmlLedStateHigh = "<big>LED is now <b>OFF</b></big><br/>\n";
const String HtmlButtons = 
    "<a href=\"LEDOn\"><button style=\"display: block; background-color: #FF0000; height: 50px; width: 100px;\">ON</button></a><br/>"
    "<a href=\"LEDOff\"><button style=\"display: block; background-color: #00FF00;  height: 50px; width: 100px;\">OFF</button></a><br/>";
    
const String HtmlCloseCenter = "</center>";

const char *ssid = "NodeAPtest";
const char *password = "password";

const int output1 = D1;
#define output1_OFF digitalWrite(output1, LOW)
#define output1_ON  digitalWrite(output1, HIGH)

int stateLED = LOW;

ESP8266WebServer server(80);

void handleRoot() {
    response();
}

void handleLedOn() {
  stateLED = LOW;
  output1_ON;
  response();
}

void handleLedOff() {
  stateLED = HIGH;
  output1_OFF;
  response();
}


void response(){
  String htmlRes = HtmlHtml + HtmlCenter;
  htmlRes +=  HtmlTitle;
  if(stateLED == LOW){
    htmlRes += HtmlLedStateLow;
  }else{
    htmlRes += HtmlLedStateHigh;
  }
  htmlRes += HtmlButtons;
  htmlRes += HtmlCloseCenter; 
  htmlRes += HtmlHtmlClose;

  server.send(200, "text/html", htmlRes);

}

void setup() {
    delay(1000);
    Serial.begin(115200);
    Serial.println();
	 
	  WiFi.mode(WIFI_AP);
    //WiFi.softAP(ssid, password);  //or 
    WiFi.softAP(ssid);
    
    IPAddress apip = WiFi.softAPIP();
    Serial.print("visit: \n");
    Serial.println(apip);
    server.on("/", handleRoot);
    server.on("/LEDOn", handleLedOn);
    server.on("/LEDOff", handleLedOff);
    server.begin();
    Serial.println("HTTP server beginned");
    pinMode(output1, OUTPUT);
    output1_OFF;
}

void loop() {
    server.handleClient();
}
